package modes

import (
	"fmt"
	"time"
)

/*继续上次练习表*/
type UsInfo struct {
	Id      int64  `json:"coll_id" xorm:"id"`      //课程收藏id
	UId     int64  `json:"coll_uid" xorm:"uid"`    //学员id
	SId     int64  `json:"coll_sid" xorm:"sid"`    //科目id
	Type    int    `json:"type" xorm:"type"`       //1：已交卷，0未交卷
	Content string `json:"content" xorm:"content"` //content
	At      int64  `json:"coll_at" xorm:"at"`      //上次进入时间
}

func (this *UsInfo) TableName() string {
	return "us_info"
}
func (this *UsInfo) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *UsInfo) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *UsInfo) GetByUS() (bool, error) {
	return Db(0).Where("uid=? and sid=? ", this.UId, this.SId).Get(this)
}

func (this *UsInfo) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *UsInfo) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *UsInfo) Count(where string) (int64, error) {
	var val UsInfo
	return Db(0).Where(where).Count(&val)
}
func (this *UsInfo) Update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}
func (this *UsInfo) UpdateById() (int64, error) {
	this.Type = 0
	return Db(0).Where("id=?", this.Id).Cols("content,at,type").Update(this)
}

func (this *UsInfo) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.Update(where, field)
}

func (this *UsInfo) where(fage, count, page int, where, field string) ([]UsInfo, error) {
	list := make([]UsInfo, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *UsInfo) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("uid = %d ", this.UId)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}

func (this *UsInfo) Lookups(val *Pager) error {
	list := make([]UsInfo, 0)
	val.TName = "UsInfo"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.at", val.TName) // 时间排序
	default:
		field = fmt.Sprintf("%s.at", val.TName) // 状态
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	return err

}
